import React, {Component} from "react";
import {connect} from "react-redux";
import * as actions from "../../actions";
import {Button,Collection,CollectionItem,Row,Col,ProgressBar,Preloader,Input} from "react-materialize";
import SkyLight from 'react-skylight';
import {Redirect} from "react-router-dom";
import YouTube from "react-youtube";
import Countdown from 'react-countdown-now';
import _ from "lodash";
import dateFormat from "dateformat";
import Seperator from "../common/Seperator";
import {I18n} from 'react-redux-i18n';
import {DISCLAIMER_CONTENT} from "../../config/text";

const renderer = ({ days,hours, minutes, seconds, completed }) => {
  if (completed) {
    // Render a completed state
    return <span>已截止</span>;
  } else if (!seconds && !minutes && !hours && !days) {
    return <span>待定</span>;
  } else {
    // Render a countdown
    return <span>{days}:{hours}:{minutes}:{seconds}</span>;
  }
};

class DetailItem extends Component {
  render(){
    const { type, content } = this.props;
    return(
      <Row style={{fontSize:"0.9em"}}>
        <Col className="textleft offset-s1" s={5}>{type}</Col>
        <Col className="textright" s={5}>{content}</Col>
      </Row>
    );
  }
}

class ProjectDetail extends Component {

  constructor(props){
    super(props);
    this.state = {
      firstCheck:false,
      secondCheck:false,
      thirdCheck:false,
      fourthCheck:false,
      fifthCheck:false
    }
  }

  componentDidMount(){
    const { projectId } = this.props.match.params;
    this.props.fetchSingleProject(projectId);
  }

  goToPlaceOrder(){
    const { projectId } = this.props.match.params;
    this.props.history.push(`/projects/${projectId}/placeorder`);
  }

  goToWeb(){
    const { webURL } = this.props.project;
    var win = window.open(webURL, '_blank');
    win.focus();
  }
  render(){
    const youtubeOpts = {
      width:"100%",
      playerVars: {
        autoplay: 0
      }
    };

    if (!this.props.project) {
      return <div className="preloaderContainer"><Preloader className="loadIndicator" flashing/></div>;
    } else {
      const handleFinish = () => {};
      const { imageURL_Small,name,summary,videoURL,content,expertRate,raised,startDate,endDate,whitepaperURL,teamURL,saleContent,allocation,remainingRoom } = this.props.project;
      const startDateString = startDate? dateFormat(startDate,"yyyy-mm-dd") : "待定";
      const endDateString = endDate? dateFormat(endDate,"yyyy-mm-dd") : "待定";
      let canInvest = (remainingRoom > 0 && Date.parse(endDate) > Date.now() && Date.parse(startDate) < Date.now());
      if (remainingRoom > 0 && !endDate && Date.parse(startDate) < Date.now()) {
        canInvest = true;
      }

      let investButtonTitle = I18n.t('PROJECT_INVEST');
      if (!canInvest && Date.parse(startDate) > Date.now()) {
        investButtonTitle = "即将开始";
      } else if (!canInvest && !startDate) {
        investButtonTitle = "即将开始";
      } else if (!canInvest && remainingRoom <= 0) {
        investButtonTitle = "已额满";
      } else if (!canInvest && Date.parse(endDate) < Date.now()) {
        investButtonTitle = "已截止";
      }

      let raisedValue = `${remainingRoom < 0 ? allocation : parseInt(allocation - remainingRoom)} ETH`;
      return (
        <div>
        <Row>
          {/* LEFT */}
          <Col s={8} >
            {/* Header */}
            <Row className="head">
              <Col s={2} ><img src={imageURL_Small}></img></Col>
              <Col s={10} >
                <h5>{name}</h5>
                <p className="summary">{summary}</p>
              </Col>
            </Row>
            <Seperator margin="30px" color="black"/>
            {/* Youtube */}
            <YouTube
              videoId={_.last(videoURL.split("/"))}
              opts={youtubeOpts}
              onReady={this._onReady}
            />
            {/* Content */}
            <div style={{marginTop:"20px"}}>
              <p className="saleContent">{saleContent}</p>
              <h5 style={{paddingBottom:"5px",fontSize:"1.1em", borderBottom:"1px solid #000", display:"inline"}}>{I18n.t('PROJECT_CONTENT')}</h5>
              <p className="content">{content}</p>
              <h5 style={{paddingBottom:"5px",fontSize:"1.1em", borderBottom:"1px solid #000", display:"inline"}}>{I18n.t('PROJECT_WHITEPAPER')}</h5>
              <p className="content"><a href={whitepaperURL} target="_blank">{whitepaperURL}</a></p>
              <h5 style={{paddingBottom:"5px",fontSize:"1.1em", borderBottom:"1px solid #000", display:"inline"}}>{I18n.t('PROJECT_TEAM')}</h5>
              <p className="content"><a href={teamURL} target="_blank">{teamURL}</a></p>
            </div>
          </Col>
          {/* RIGHT */}
          <Col s={4}>
            {/* RATE */}
            <div className="rateSection">
              <h4>{expertRate}</h4>
              <p style={{fontSize:"0.8em"}}>​{I18n.t('PROJECT_SCORE')}</p>
            </div>
            {/* RAISED */}
            <ProgressBar progress={parseInt(100*(allocation - remainingRoom)/allocation)}/>
            <h5 style={{fontSize:"1em"}}>{raisedValue}</h5>
            <p style={{fontSize:"0.8em"}}>{I18n.t('RAISED')}</p>
            {/* DATA */}
            <div className="detailInfo">
              <h5 style={{fontSize:"1.2em",paddingBottom:"10px"}}>{I18n.t('PROJECT_DATA')}</h5>
              <Seperator margin="30px" color="black"/>
              <p style={{fontSize:"0.8em"}}>{I18n.t('PROJECT_SCHEDULE')}​</p>
              <p style={{fontSize:"0.8em"}}>{`${startDateString} - ${endDateString}`}</p>

              <div className="countDown">
               <Countdown date={ Date.now()>Date.parse(startDate) ? endDate : startDate}
                          intervalDelay={0}
                          precision={3} renderer={renderer} />
               <p style={{fontSize:"0.7em"}}>Day   Hour   Min   Sec</p>

                <Seperator margin="30px" color="black"/>
                <div className="detailTable">
                  {this.renderDetail()}
                <div className="buttonSec">
                  <Button onClick={() => this.disclaimer.show()} disabled={!canInvest}>{investButtonTitle}</Button>
                  <Button onClick={this.goToWeb.bind(this)}>{I18n.t('PROJECT_WEBSITE')}</Button>
                  <SkyLight hideOnOverlayClicked ref={ref => this.disclaimer = ref} title={I18n.t('DISCLAIMER')}>
                    <div className="disclaimer">
                      <p style={{textAlign:"justify",marginLeft:"15px",marginRight:"15px"}}>{DISCLAIMER_CONTENT}</p>
                      <Input name='group1'
                             type='checkbox'
                             value="firstCheck"
                             label={this.props.project.restrictMode?I18n.t('DISCLAIMER_COUNTRY_RESTRICT'):I18n.t('DISCLAIMER_COUNTRY')}
                             onChange={(e)=>{this.setState({firstCheck:e.target.checked})}} />
                      <br/>
                      <Input name='group1'
                             type='checkbox'
                             value="secondCheck"
                             label={I18n.t('DISCLAIMER_RISK1')}
                             onChange={(e)=>{this.setState({secondCheck:e.target.checked})}} />
                             <br/>
                      <Input name='group1'
                             type='checkbox'
                             value="thirdCheck"
                             label={I18n.t('DISCLAIMER_RISK2')}
                             onChange={(e)=>{this.setState({thirdCheck:e.target.checked})}} />
                             <br/>
                      <Input name='group1'
                             type='checkbox'
                             value="fourthCheck"
                             label={I18n.t('DISCLAIMER_RISK3')}
                             onChange={(e)=>{this.setState({fourthCheck:e.target.checked})}} />
                             <br/>
                      <Input name='group1'
                             type='checkbox'
                             value="fifthCheck"
                             label={I18n.t('DISCLAIMER_RISK4')}
                             onChange={(e)=>{this.setState({fifthCheck:e.target.checked})}} />
                    </div>
                    <Button disabled={(this.state.firstCheck&&
                                       this.state.secondCheck&&
                                       this.state.thirdCheck&&
                                       this.state.fourthCheck&&
                                       this.state.fifthCheck)?false:true}
                            onClick={this.goToPlaceOrder.bind(this)}>{I18n.t('PROJECT_INVEST')}
                    </Button>
                  </SkyLight>
                </div>
                </div>
              </div>
            </div>
          </Col>
        </Row>

        </div>
      )
    }
  }

  renderDetail(){
    const { symbol,tokenReleaseDate,price,softCap,hardCap } = this.props.project;
    return(
      [
        <DetailItem key="symbol" type={I18n.t('SYMBOL')} content={symbol}/>,
        <DetailItem key="releasedate" type={I18n.t('RELEASE_TOKEN_DATE')} content={tokenReleaseDate ? dateFormat(tokenReleaseDate,"yyyy-mm-dd") : "待定"}/>,
        <DetailItem key="price" type={I18n.t('PRICE')} content={price}/>,
        <DetailItem key="platform" type={I18n.t('PLATFORM')} content="Ethereum"/>,
        <DetailItem key="currency" type={I18n.t('AVALIBLE_CURRENCY')} content="ETH"/>,
        <DetailItem key="softcap" type={I18n.t('SOFTCAP')} content={softCap}/>,
        <DetailItem key="hardcap" type={I18n.t('HARDCAP')} content={hardCap}/>
      ]
    );
  }
}

function mapStateToProps(state, ownProps){
  return {
            project: state.project[ownProps.match.params.projectId],
            locale:state.i18n.locale
          };
}

export default connect(mapStateToProps,actions)(ProjectDetail);

